package com.demo.user;

import com.demo.blog.BlogInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;

import java.util.List;

/**
 * Created by Ht on 2017/6/11.
 */
public class HdUserController extends Controller{
    private final HdUserService service = new HdUserService();
    /*
    public void index() {
        render("index.html");
    }
    */

    /**
     * 默认请求login页面
     */
    public void index(){
        redirect("/usr/list");
    }

    /**
     * 请求login页面
     */
    public void home(){
        HdUser usr = getSessionAttr("_hd_user");

        if(usr !=null){
            setAttr("usr_name",usr.get("uname"));
            render("/index/home.html");
        }else{
            render("/index/index.html");
        }
    }

    public void logout(){
        removeSessionAttr("_hd_user");
        redirect("/usr/home");
    }

    public void login(){
        //renderText("Hello,world2");
        String v1= getPara("name");
        String v2= getPara("pass");

        //
        HdUser usr = getSessionAttr("_hd_user");
        if(usr ==null){
            usr = getModel(HdUser.class);
            usr = usr.dao().findFirstByWhere("where uname=?",v1);
            if(usr!=null && usr.get("upass").equals(v2)){
                //验证通过
                setSessionAttr("_hd_user",usr);
            }else{
                render("/index/login_failed.html");
                return;
            }
        }
        redirect("/usr/home");
    }

    public void add(){
        //设置默认值
        render("usr_edit.html");
        new HdUser().myset();

        redirect("/usr/list");
    }

    public void save(){
        //提取参数，调用service的name、id等，然后返回一个用户添加的结果消息
        String name = getPara("name");
        String pass = getPara("pass");
        String phone = getPara("phone");
        setAttr("name",name);

        HdUser usr = getModel(HdUser.class);
        usr.put("uname",name);
        usr.put("upass",pass);
        usr.put("phone",phone);

        usr.save();
        //getModel(HdUser.class).save();
        redirect("/usr/list");
    }

    public void delete(){
        int id= getParaToInt(0,0);
        if(id>0){
            HdUser usr = getModel(HdUser.class);
            usr.dao().deleteById(id);
        }
        redirect("/usr/list");
    }

    public void list(){
        int i = getParaToInt(0,10);
        HdUser usr = getModel(HdUser.class);
        List<HdUser> users = usr.findByWhere("");
        //users.
        setAttr("hdul",users);

        render("/usr/list.html");
    }


}
